package com.water.gateway.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

@RestController
public class AuthStatusController {

	@GetMapping("/api/logout")
	public Mono<Void> logout(ServerWebExchange exchange) {
		 return exchange.getSession()
		            .flatMap(webSession -> webSession.invalidate());
	}

	@GetMapping("/api/auth/status")
	public Mono<Map<String, Object>> authStatus() {
		return ReactiveSecurityContextHolder.getContext().map(ctx -> ctx.getAuthentication()).map(authentication -> {
			Map<String, Object> result = new HashMap<>();
			if (authentication != null && authentication.isAuthenticated()
					&& !"anonymousUser".equals(authentication.getPrincipal())) {
				result.put("authenticated", true);
				result.put("username", authentication.getName());
				result.put("authorities", authentication.getAuthorities());
			} else {
				result.put("authenticated", false);
			}
			return result;
		}).defaultIfEmpty(new HashMap<>() {
			private static final long serialVersionUID = 1L;
			{
				put("authenticated", false);
			}
		});
	}
}